
from pandas import DataFrame
from pymysql.connections import Connection

from datareport.api import ImageUtil
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style
from datareport.impl import StaticDF


@style()
class JiHua_ErJidangZuZhiFenBu_16(BaseParagraph):
    """
    二级党组织分布
    """

    def __init__(self):
        super().__init__()
        self.text = '''（1）从二级党组织分布来看：{}组织生活计划场次最高，\
为{}场次，平均{}场/月/支部；{}(总场次为{})组织生活计划场次均值最大，\
为{}场次/月/支部。{}组织生活计划较低，平均为{}'''
        self.sort = 7
        self.section = 1

    def plot(self, result, plt):
        pass


    def getData(self, result):
        pass

    def start(self, conn: Connection, year, plt):
        # cursor=conn.cursor()

        df = StaticDF.getDF()
        df['num'] = 1
        count_Org_df = df.groupby('partyOrgName')['num'].count()
        # 场次最高
        max_Org = count_Org_df.idxmax()
        max_df: DataFrame = df[df['partyOrgName'] == count_Org_df.idxmax()]
        partyBranchNames = len(max_df['partyBranchName'].drop_duplicates())
        max_avg = round(len(max_df) / (12 * partyBranchNames),1)  # 场次最大的均
        count_Org_df_index=count_Org_df.reset_index(drop=False)
        count_Org_df_index['avg'] = count_Org_df_index['partyOrgName'].apply(lambda x: branchCount(x, df)) # 这一行代码可以让索引调用branchCount函数
        count_Org_df_index.sort_values('avg', ascending=False, inplace=True)
        avg_max=count_Org_df_index['partyOrgName'].values[0] # 均值最大的org
        text='{}场/月/支部'
        all_text=[]
        ## 按照机构计划场次排序
        for e in count_Org_df.sort_values().index[0:3].values:
            avg=count_Org_df_index[count_Org_df_index['partyOrgName']==e].iloc[0].at['avg']
            text=text.format(avg)
            all_text.append(text)
        self.text = self.text.format(max_Org,
                                     len(max_df),
                                     max_avg,
                                     avg_max,
                                     len(df[df['partyOrgName']==avg_max]),
                                     count_Org_df_index['avg'].values[0],
                                     '、'.join(count_Org_df.sort_values().index[0:3].values),
                                     '和'.join(all_text))
        self.image=ImageUtil.plot(count_Org_df.reset_index(drop=False),'二级党组织计划分布','','计划数量')


def branchCount(x, df):
    x_df = df[df['partyOrgName'] == x]
    bs = len(x_df['partyBranchName'].drop_duplicates())
    avg = round(len(x_df) / (12 * bs), 1)
    return avg
